#include <stdio.h>
#include <error.h>
#include <stdlib.h>

unsigned int niter;


void qsort2(int v[], int left, int right)
{
    int i, last;
    void swap(int v[], int i, int j);

    niter++;

    if (left >= right)
        return;
    swap(v, left, (left + right)/2);
    last = left;
    for (i = left+1; i <= right; i++)
        if (v[i] < v[left])
            swap(v, ++last, i);
    swap(v, left, last);
    qsort2(v, left, last-1);
    qsort2(v, last+1, right);
}

void swap(int v[], int i, int j)
{
    int temp;

    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

int main(int argc, char *argv[])
{
    int i;
    int v[1000];

    if ((argc < 2) || (argc > 1001))
        error(EXIT_FAILURE, 0, "Wrong number of arguments.\n"
                "Usage: %s <number> ...", argv[0]);

    for (i = 0; i < (argc - 1); i++)
        v[i] = atoi(argv[i + 1]);

    for (i = 0; i < (argc - 1); i++)
        printf("%d --> %d\n", i, v[i]);

    qsort2(v, 0, argc - 2);

    for (i = 0; i < (argc - 1); i++)
        printf("%d --> %d\n", i, v[i]);

    printf("niter: %u\n", niter);

    exit(EXIT_SUCCESS);
}
